package org.ricks.ioc.definition.filed;

import org.ricks.ioc.RicksContext;
import org.ricks.ioc.utils.IocException;
import org.ricks.ioc.utils.StringUtils;

import java.lang.reflect.Field;

/**
 * 一个被IOC容器所管理的JavaBean定义描述类.
 */
public class DefaultFieldDefinition implements FieldDefinition {

    protected final Field field;
    protected final String beanName;
    protected final Class<?> fieldClass;

    public DefaultFieldDefinition(Field field, String beanName) {
        this(field, field.getType(), beanName);
    }

    protected DefaultFieldDefinition(Field field, Class<?> fieldClass, String beanName) {
        this.field = field;
        this.beanName = beanName;
        this.fieldClass = fieldClass;
        this.field.setAccessible(true);
    }

    @Override
    public void injection(Object single) {
        //获取属性的beanid
        Object bean = RicksContext.me().getInstance(fieldClass);
        try {
            field.setAccessible(true);
            field.set(single,bean);
        } catch (Exception e) {
            throw new IocException(StringUtils.format("IOC依赖注入失败 - {} - {}", single.getClass().getSimpleName(), bean),e);
        }
    }

}